package com.wutianyi.pool.concurrent.example;

import java.util.concurrent.CyclicBarrier;

public class BenchMarkTest {
	
	private Counter counter;
	private CyclicBarrier barrier;
	private int threadNum;
	private int loopNum;
	private String testName;
	
	public BenchMarkTest(Counter counter, int threadNum, int loopNum, String testName) {
		this.counter = counter;
		this.loopNum = loopNum;
		this.threadNum = threadNum;
		this.testName = testName;
		barrier = new CyclicBarrier(threadNum +1);
	}
	
	public static void main(String[] args) {
		int threadNum = 5000;
		int loopNum = 100;
		new BenchMarkTest(new SynchronizedBenchmarkDemo(), threadNum, loopNum, "内部锁").test();
		new BenchMarkTest(new ReentrantLockFairBeanchmarkDemo(), threadNum, loopNum, "公平重入锁").test();
		new BenchMarkTest(new ReentrantLockUnfairBeanchmarkDemo(), threadNum, loopNum, "不公平重入锁").test();
	}
	
	public void test() {
		try {
			for(int i = 0; i < threadNum; i ++) {
				new TestThread(counter, loopNum).start();
			}
			long start = System.currentTimeMillis();
			barrier.await();
			barrier.await();
			long end = System.currentTimeMillis();
			System.out.println(this.testName + " count value: " + counter.getValue());
			System.out.println(this.testName + " 花费时间: " + (end - start) + "毫秒");
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	class TestThread extends Thread {
		int loopNum = 100;
		private Counter counter;
		public TestThread(final Counter counter, int loopNum) {
			this.counter = counter;
			this.loopNum = loopNum;
		}
		
		public void run() {
			try {
				barrier.await();
				for(int i = 0; i < this.loopNum; i ++) {
					counter.increment();
				}
				barrier.await();
			} catch (Exception e) {
				
			}
		}
	}
	
}
